package com.project.taller2.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.project.taller2.dao.GenericDao;
import com.project.taller2.obj.AbstractElement;

@Repository
@SuppressWarnings("unchecked")
public abstract class GenericDaoImpl<T extends AbstractElement> implements GenericDao<T> {

	@Autowired
	private SessionFactory sessionFactory;
	protected Class<T> prototypeClass;
	
	public GenericDaoImpl() {
	}
	
	public GenericDaoImpl(Class<T> type) {
		this.prototypeClass = type;
	}
	
	@Override
	public Long delete(T element) {
		// TODO ver que pasa cuando elimino algo que no existe
		sessionFactory.getCurrentSession().delete(element);
//		Contact contact = (Contact) sessionFactory.getCurrentSession().load(
//				Contact.class, id);
//		if (null != contact) {
//			sessionFactory.getCurrentSession().delete(contact);
//		}
		return element.getId();
	}
	
	@Override
	public Long save(T element) {
		sessionFactory.getCurrentSession().save(element);
		return element.getId();
	}
	
	@Override
	public List<T> getAll() {
		return sessionFactory.getCurrentSession().createCriteria(prototypeClass).list();
	}
	
	@Override
	public T getById(Long id) {
		List<T> list = getByField("id", id);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		
		return list.get(0);
	}

	@Override
	public List<T> getByField(String field, Object value) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(prototypeClass);
		criteria.add(Restrictions.like(field, value));
		criteria.addOrder(Order.asc(field));
		return criteria.list();
	}
	
}
